
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class ShowHideWidget extends StatefulWidget {

  Widget child;
  int? milliseconds;
  bool? showToHide;
  bool? repeat;

  ShowHideWidget(this.child, {this.milliseconds, this.showToHide, this.repeat, Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _ShowHideState();
}

class _ShowHideState extends State<ShowHideWidget> with SingleTickerProviderStateMixin {

  late AnimationController controller;
  late Animation<double> animation;

  @override
  void initState() {
    super.initState();
    controller = AnimationController(vsync: this, duration: Duration(milliseconds: widget.milliseconds ?? 3000));
    double begin = 0.0;
    double end = 1.0;
    if(widget.showToHide ?? false){
      begin = 1.0;
      end = 0.0;
    }
    animation = Tween(begin: begin, end: end).animate(controller)
      ..addListener(() {
        setState(() {});
      })
      ..addStatusListener((status) {
        if (status == AnimationStatus.completed) {
          if(widget.repeat ?? false) {
            controller.reverse();
          }
        } else if (status == AnimationStatus.dismissed) {
          controller.forward();
        }
      });

    controller.forward();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedOpacity(
      opacity: animation.value,
      duration: const Duration(milliseconds: 0),
      child: widget.child,
    );
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }
}